package common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;



/**
 * This class contains some useful function of file-control
 * @version v1.0.1
 * @author Romam
 * @Date 09.18.2011
 */
public class FileControlSet {
	
	private String RootPath;
	
	
	/**
	 * Default empty constructor
	 * @author Romam
	 */
	public FileControlSet(){
		//Constructor
	}
		
	/**
	 * Delete the given file with its absolute location(String Location)
	 * @param Location - file path
	 * @throws Exception
	 */
	public void DeleteFile(String Location) throws Exception{
		File fileloc = new File(Location);
		if(fileloc.isDirectory()){
			System.out.println("NOT A FILE!");
		}else{
			fileloc.delete();
		}
	}
	
	/**
	 * Delete the given directory with its absolute location(String Locations)
	 * @param Location - directory path
	 * @return false if this is a file location / true if this is a directory
	 * @throws Exception
	 * @author Romam
	 */
	public void DeleteDir(String Location) throws Exception{
		File fileloc = new File(Location);
		if(fileloc.isDirectory()){
			fileloc.delete();
		}else{
			System.out.println("NOT A DIR");
		}
	}
	
	/**
	 * Build the assigned directory
	 * @param String Dir - assigned the directory to build
	 * @throws Exception
	 * @author Romam
	 */
	public void BuildDir(String Dir) throws Exception{
		File files = new File(Dir); 
		files.mkdirs(); 
	}
	
	/**
	 * Get the file directory
	 * @param Location - file location
	 * @return 
	 */
	public String getDir(String Location){
		File file = new File(Location);
		if(file.isDirectory()==true){
			return Location;
		}else{
			return file.getParent();
		}
	}
		
	/**
	 * Copy file
	 * @param From - the source file location
	 * @param To - the target file directory
	 * @param Filename - the target file name
	 * @throws Exception
	 * @author Romam
	 */
	public void CopySingleFile(String From, String To, String Filename) throws Exception{
		FileInputStream fi=new FileInputStream(From);
		BufferedInputStream in=new BufferedInputStream(fi);
		File files = new File(To,Filename); 		
		files.getParentFile().mkdirs(); 
		FileOutputStream fo=new FileOutputStream(To+Filename);
		BufferedOutputStream out=new BufferedOutputStream(fo);
		byte[] buf=new byte[1024];
		int len=in.read(buf);
		while(len!=-1){
			out.write(buf, 0, len);
			len=in.read(buf);
		}
		
		out.close();
		fo.close();
		in.close();
		fi.close();
	}
	
	/*public static void main(String[] args){
		try {
			new FileControlSet().CopyDirectory("E:/VM/", "E:/CommPicByGroup/");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void CopyDirectory(String From, String To) throws IOException{
		FileInputStream fi=new FileInputStream(From);		
		BufferedInputStream in=new BufferedInputStream(fi);
		File files = new File(To);
		files.getParentFile().mkdirs();
		FileOutputStream fo=new FileOutputStream(To);
		BufferedOutputStream out=new BufferedOutputStream(fo);
		byte[] buf=new byte[1024];
		int len=in.read(buf);
		while(len!=-1){
			out.write(buf, 0, len);
			len=in.read(buf);
		}
		out.close();
		fo.close();
		in.close();
		fi.close();
	}*/
	
	/**
	 * Find out the file paths that meets the given path(String Path) and an filter file type(String FilteringType)
	 * @param Path - assign searching location/directory
	 * @param FilteringType - assign filter file type
	 * @return list - all the directory/location of which meets the assigned conditions 
	 * @author Romam
	 */
	public List Find_FILTER(String Path,String FilteringType){
		RootPath = Path;	
		return findFiles_FILTER(RootPath,FilteringType);
	}	
	
	/**
	 * Find out the file paths that meets the given path(String Path) and an assigned file type(String AssignedType)
	 * @param Path - assign searching location/directory
	 * @param AsignedType - assign searching file type
	 * @return list - all the directory/location of which meets the assigned conditions 
	 * @author Romam
	 */
	public List Find_Asigned(String Path,String AssignedType){
		RootPath = Path;		
		return findFiles_Asigned(RootPath,AssignedType);
	}
	
	/**
	 * Find out the all the file paths that meets the given path(String Path)
	 * @param Path - assign searching location/directory
	 * @return list - all the directory/location of which meets the assigned conditions 
	 * @author Romam
	 */
	public List Find_NoFilter(String Path){
		RootPath = Path;	
		return findFiles_NO_FILTER(RootPath);
	}
	
	public List Find_MeetRegex(String Path, String regex){
		RootPath = Path;
		return findFiles_MeetRegex(RootPath, regex);
	}
	
	/**
	 * Delete all the files in the assigned type(String AssignedType) in the given location(String Location)
	 * @param Location - the given location
	 * @param AssignedType - the assigned assigned type
	 * @throws Exception
	 * @author Romam
	 */
	public void DeleteFiles_Asigned(String Location,String AssignedType) throws Exception{
		List Filelist = findFiles_Asigned(Location,AssignedType);
		for(Iterator iter = Filelist.iterator();iter.hasNext();){
			File filecur = new File(iter.next().toString());
			System.out.println("DELETING :" + filecur.getName());
			filecur.delete();				
		}
	}
	
	
	/**
	 * Delete all the files in the given location(String Location) except the files in the assign file type(String FilterType)
	 * @param Location - the given location
	 * @param FilterType - the assign file type
	 * @throws Exception
	 * @author Romam
	 */
	public void DeleteFiles_Filter(String Location,String FilterType) throws Exception{
		List Filelist = findFiles_FILTER(Location,FilterType);
		for(Iterator iter = Filelist.iterator();iter.hasNext();){
			File filecur = new File(iter.next().toString());
			System.out.println("DELETING :" + filecur.getName());
			filecur.delete();				
		}
	}
	
	//Private Functions
	private static List findFiles_FILTER(String baseDirName,String FilteringType) {
		List fileList = new ArrayList();
		File baseDir = new File(baseDirName);
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("查找文件失败：" + baseDirName + "不是一个目录!");
			return fileList;
		}
		String tempName = null;
		Queue queue = new LinkedList();
		queue.offer(baseDir);
		File tempFile = null;
		while(!queue.isEmpty()){
			tempFile = (File) queue.poll();
		    if(tempFile.exists() && tempFile.isDirectory()) 
		    {
		    	File[] files = tempFile.listFiles();
		    	for(int i = 0; i < files.length; i++) {
		    		if(files[i].isDirectory())
		    			queue.offer(files[i]);
		    		else
		    		{
		    			tempName = files[i].getName();
		    			if(tempName.endsWith(FilteringType))
		    				continue;
		    			fileList.add(files[i].getAbsoluteFile());
		    		}
		    	}
		    }
		}
		return fileList;
	}
	
	private static List findFiles_NO_FILTER(String baseDirName) {
		List fileList = new ArrayList();
		File baseDir = new File(baseDirName);
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("查找文件失败：" + baseDirName + "不是一个目录!");
			return fileList;
		}
		String tempName = null;
		Queue queue = new LinkedList();
		queue.offer(baseDir);
		File tempFile = null;
		while(!queue.isEmpty()){
			tempFile = (File) queue.poll();
		    if(tempFile.exists() && tempFile.isDirectory()) 
		    {
		    	File[] files = tempFile.listFiles();
		    	for(int i = 0; i < files.length; i++) {
		    		if(files[i].isDirectory())
		    			queue.offer(files[i]);
		    		else
		    		{
		    			tempName = files[i].getName();		    			
		      			fileList.add(files[i].getAbsoluteFile());
		    		}
		    	}
		    }
		}
		return fileList;
	}
	
	private static List findFiles_Asigned(String baseDirName, String AsignedType) {
		List fileList = new ArrayList();
		File baseDir = new File(baseDirName);
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("查找文件失败：" + baseDirName + "不是一个目录!");
			return fileList;
		}
		String tempName = null;
		Queue queue = new LinkedList();
		queue.offer(baseDir);
		File tempFile = null;
		while(!queue.isEmpty()){
			tempFile = (File) queue.poll();
		    if(tempFile.exists() && tempFile.isDirectory()) 
		    {
		    	File[] files = tempFile.listFiles();
		    	for(int i = 0; i < files.length; i++) {
		    		if(files[i].isDirectory())
		    			queue.offer(files[i]);
		    		else
		    		{
		    			tempName = files[i].getName();
		    			if(tempName.endsWith(AsignedType))
		    				fileList.add(files[i].getAbsoluteFile());
		    			else
		    				continue;
		    		}
		    	}
		    }
		}
		return fileList;
	}
	
	private static List findFiles_MeetRegex(String baseDirName, String regex) {
		List fileList = new ArrayList();
		File baseDir = new File(baseDirName);
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("查找文件失败：" + baseDirName + "不是一个目录!");
			return fileList;
		}
		String tempName = null;
		Queue queue = new LinkedList();
		queue.offer(baseDir);
		File tempFile = null;
		while(!queue.isEmpty()){
			tempFile = (File) queue.poll();
		    if(tempFile.exists() && tempFile.isDirectory()) 
		    {
		    	File[] files = tempFile.listFiles();
		    	for(int i = 0; i < files.length; i++) {
		    		if(files[i].isDirectory())
		    			queue.offer(files[i]);
		    		else
		    		{
		    			tempName = files[i].getName();
		    			if(tempName.split(regex).length>=2)		    			
		    				fileList.add(files[i].getAbsoluteFile());
		    			else
		    				continue;
		    		}
		    	}
		    }
		}
		return fileList;
	}
	
	public List findCurrentLevel(String baseDirName, String AsignedType){
		List fileList = new ArrayList();
		File baseDir = new File(baseDirName);
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("查找文件失败：" + baseDirName + "不是一个目录!");
			return fileList;
		}
		String tempName = null;
		File[] files = baseDir.listFiles();
    	for(int i = 0; i < files.length; i++) {
    		if(files[i].isDirectory())
    			continue;
    		else
    		{
    			tempName = files[i].getName();
    			if(AsignedType == null || tempName.endsWith(tempName)){
    				fileList.add(files[i]);
    			}
    		}
    	}
		 
		return fileList;
	}
}
